package com.sql.handler.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.sql.handler.Deploy;

public class SerializableUtil implements ISerializableFileName{ 
	
	/**
	 * 序列化 - 写入
	 * @param aFileName
	 * @param aObject
	 * @return
	 * @throws IOException
	 */
	public static boolean writeObject(String aFileName, Object aObject) throws IOException{
		Deploy deploy = (Deploy) aObject;
		if(!deploy.getIsSaveInfo()){
			return false;
		}

		if(aObject == null || aFileName == null || aFileName.equals("")){
			return false;
		}
		final File file = new File(aFileName);  
		  if (file.exists()) {
		   file.delete();
	    }
		file.createNewFile();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
		objectOutputStream.writeObject(aObject);
		objectOutputStream.close();	
		/*监听程序退出，删除序列化文件*/
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				super.run();
				if(file.exists()){
					file.delete();
				}
			}
		});
		return true;
	}
	
	/**
	 * 序列化 - 读取
	 * @param aFileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Object readObject(String aFileName) throws FileNotFoundException, IOException, ClassNotFoundException{
		if(aFileName == null || aFileName.equals("")){
			return false;
		}
		File file = new File(aFileName);  
		if (!file.exists()) {
   	    return null;
	    }
   	    ObjectInputStream objectOutputStream = new ObjectInputStream(new FileInputStream(file));
	    return objectOutputStream.readObject();	   
	}
	
	/**
	 * 删除存入本地的文件
	 * @param aFileName
	 */
	public static void deleteObject(String aFileName){
		if(aFileName == null || aFileName.equals("")){
			return;
		}
		File file = new File(aFileName);  
		  if (file.exists()) {
		  file.delete();
	    }
	}
}
